<?php
/**
 * +----------------------------------------------------------------------
 * | Copyright © Sogu Technologies Co. Ltd 2018-2050 All rights reserved.
 * +----------------------------------------------------------------------
 * | File name: MoneyPlatformRequest.php
 * +----------------------------------------------------------------------
 * | Author: sam
 * +----------------------------------------------------------------------
 * | Description: 资金平台请求类
 * +----------------------------------------------------------------------
 * | Others: 其他内容的说明
 * +----------------------------------------------------------------------
 * | History: 修改历史记录列表，每条修改记录应包含修改日期、修改者及修改内容简述
 * +----------------------------------------------------------------------
 * | 1.Date: 2018/12/25 Author: sam Modification: 创建
 * +----------------------------------------------------------------------
 */

namespace App\Library\Guzzle;


use App\Constant\ThirdMoneyCode;
use App\Constants\RedisKey;
use App\Facades\SamLogFacade;
use App\Library\Traits\PlatformRequest;
use App\Models\RepaySummary;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

/**
 * Class MoneyPlatformRequest
 *
 * Description:资金平台请求方法类
 * Author: Sam
 * DateTime: 2019/1/6 9:35
 * @package App\Library\Guzzle
 */
class MoneyPlatformRequest
{
    use PlatformRequest;
    /**
     * 资金平台基础uri
     * @var \Illuminate\Config\Repository|mixed
     */
    protected $platform_uri;

    /**
     * 不同环境下的二级目录
     * @var
     */
    protected $second_dir;

    /**
     * 用户信息同步url
     * @var string
     */
    protected $user_info_sync = '/user/syncUser';

    /**
     * 查询用户信息同步结果url
     * @var string
     */
    protected $query_sync_user = '/user/querySyncUser';

    /**
     * 申请授信url
     * @var string
     */
    protected $loan_apply = '/loan/applyCreditAmount';

    /**
     * 放款申请url
     * @var string
     */
    protected $applyLoanUrl = '/loan/applyLoan';

    /**
     * 贷款试算url
     * @var string
     */
    protected $loan_calculate = '/loan/loanCalculate';


    /**
     * 换卡接口
     * @var string
     */
    protected $changeBankCardUrl = '/user/changeBankCard';
    /**
     * 查询授信结果url
     * @var string
     */
    protected $get_loan_apply_status = '/loan/queryCreditResult';

    /**
     * 放款结果查询接口
     * @var string
     */
    protected $loanResultUrl = '/loan/queryLoanResult';

    /**
     * 还款计划表查询url
     * @var string
     */
    protected $select_repay_plan = '/pay/repaymentPlan';

    /**
     * 提前还清试算
     * @var string
     */
    protected $repayment_repay = "/pay/aheadRepaymentPlan";

    /**
     * 主动还款
     * @var string
     */
    protected $money_repay = '/pay/repayment';

    /**
     * 主动还款结果
     * @var string
     */
    protected $money_repay_result = '/pay/repaymentResult';

    /**
     * 月保费还款
     * @var string
     */
    protected $month_insurance_repay = '/policy/month';

    /**
     * 月保费还款结果
     * @var string
     */
    protected $month_insurance_repay_result = '/policy/monthResult';

    /**
     * 资方销账代偿接口
     * @var string
     */
    protected $pay_compensate = '/pay/compensate';

    /**
     * 公共请求参数
     * @var array
     */
    protected $body = [];

    /**
     * 参数集合
     * @var
     */
    private $_pub_data;

    /**
     * 业务数据签名
     * @var
     */
    private $_pub_sign;

    /**
     * MoneyPlatformRequest constructor.
     */
    public function __construct()
    {
        $env = App::environment();
        $this->second_dir = $env == 'Pro' ? 'nfsp-gateway' : 'nfsp';
        $this->platform_uri = config('common.money_platform_base_uri');
    }

    /**
     * Description:用户信息同步请求
     * Author: Sam
     * DateTime: 2019/1/3 16:03
     * @param $data
     * @return mixed
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function userSync($data)
    {
        $this->_pub_data = [
            'realName' => $data['realName'],
            'englishName' => $data['englishName'],
            'certType' => $data['certType'],
            'certNo' => $data['certNo'],
            'gender'=>$data['gender'],
            'certValidity' => $data['certValidity'],
            'certGovernment' => $data['certGovernment'],
            'certNation'=>$data['certNation'],
            'certAddr' => $data['certAddr'],
            'maritalStatus' => $data['maritalStatus'],
            'email' => $data['email'],
            'liveCondition' => $data['liveCondition'],
            'liveProvince' => $data['liveProvince'],
            'liveCity' => $data['liveCity'],
            'liveArea' => $data['liveArea'],
            'address' => $data['address'],
            'postCode'=>$data['postCode'],
            'loanBankCode' => $data['loanBankCode'],
            'loanBankName' => $data['loanBankName'],
            'loanBankCardNo' => $data['loanBankCardNo'],
            'loanBindPhoneNo' => $data['loanBindPhoneNo'],
            'bankLineNumber' => $data['bankLineNumber'],
            'educationalLevel' => $data['educationalLevel'],
            'contactName' => $data['contactName'],
            'contactPhoneNo' => $data['contactPhoneNo'],
            'contactRelation' => $data['contactRelation'],
            'contactName2' => $data['contactName2'],
            'contactPhoneNo2' => $data['contactPhoneNo2'],
            'contactRelation2' => $data['contactRelation2'],
            'supportPopulation'=>$data['supportPopulation'],
            'positionOpt' => $data['positionOpt'],
            'companyName' => $data['companyName'],
            'companyAddress' => $data['companyAddress'],
            'companyPhone' => $data['companyPhone'],
            'salary' => $data['salary'],
            'workDuration'=>$data['workDuration'],
            'companyCategory'=>$data['companyCategory'],
            'industry'=>$data['industry'],
            'protocolNo' => $data['protocolNo'],
            'protocolDate' => $data['protocolDate'],
            'healthCondition' => $data['healthCondition'],
        ];
        foreach ($this->_pub_data as $k => $v) {
            if ($k == 'salary') {
                $this->_pub_data[$k] = doubleval($v);
            } else {
                $this->_pub_data[$k] = strval($v);
            }
        }
        $this->_pub_sign = Sign::sign($this->_pub_data, 2);
        return $this->request($this->second_dir . $this->user_info_sync, 'money');
    }

    /**
     * Description:查询用户信息同步结果
     * Author: Sam
     * DateTime: 2019/1/3 16:03
     * @param $cert_no
     * @return mixed
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function querySyncUser($cert_no)
    {
        $this->_pub_data = [
            'certNo' => $cert_no,
        ];
        $this->_pub_sign = Sign::sign($this->_pub_data, 2);
        return $this->request($this->second_dir . $this->query_sync_user, 'money');
    }

    /**
     * Description:申请授信请求
     * Author: Sam
     * DateTime: 2019/1/3 19:58
     * @param $data
     * @return mixed
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function loanApply($data)
    {
        $this->_pub_data = [
            'outCreditId' => $data['outCreditId'],
            'userId' => $data['nfsp_user_id'],
            'productNo' => config('common.money_platform_product_no'),
            'amount' => $data['amount'],
            'period' => $data['period'],
            'purpose' => $data['purpose'],
            'fileList' => [],
            'deviceIP' => $data['deviceIP'],
            'deviceGPS'=> $data['deviceGPS'],
            'deviceType' => $data['deviceType'],
            'device' => $data['device'],
            'deviceOS' => $data['deviceOS'],
            'deviceMac' => $data['deviceMac'],
            'deviceIMEI' => $data['deviceIMEI'],
            'riskId' => $data['riskId'],
        ];
        $key = RedisKey::USER_LOAN_REQUEST_DATA;
        Redis::lPush($key,json_encode($this->_pub_data,JSON_UNESCAPED_UNICODE));
        $this->_pub_sign = Sign::sign($this->_pub_data, 2);
        return $this->request($this->second_dir . $this->loan_apply, 'money');
    }


    /**
     * Description: 用户放款申请
     * Author: liuju
     * DateTime: 2019-01-04 19:58
     * @param $data
     * @return mixed
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function applyLoan($data)
    {
        $this->_pub_data = [
            'creditId' => strval($data['credit_id']),
            'preInsuranceAmt' => doubleval($data['pre_insurance_amt']),
            'amount' => doubleval($data['amount']),
            'period' => intval($data['period']),
        ];
        $this->_pub_sign = Sign::sign($this->_pub_data, 2);
        return $this->request($this->second_dir . $this->applyLoanUrl, 'money');
    }


    /**
     * Description: 银行卡换卡接口
     * Author: liuju
     * DateTime: 2019-01-04 20:07
     * @param $data
     * @param $type
     * @return mixed
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function changeBankCard($data,$type = RepaySummary::DATA_TYPE_ONE)
    {
        $this->_pub_data = [
            'userId' => $data['user_id'],
            'real_name' => $data['real_name'],
            'loanBankCardNo' => $data['card_num'],
            'loanBankCode' => $data['bank_code'],
            'loanBankName' => $data['bank_name'],
            'loanBindPhoneNo' => $data['phone_num'],
            'certNo' => $data['cert_num'],
            'certType' => $data['cert_type'],
            'protocolNo'=>$data['protocolNo'],
            'protocolDate'=>$data['protocolDate'],
            'purpose' => $data['purpose'],
        ];
        $key = sprintf(RedisKey::BANK_CARD_CHANGE_REQUEST_DATA,$data['user_id']);
        Redis::lPush($key,json_encode($this->_pub_data,JSON_UNESCAPED_UNICODE));
        $this->_pub_sign = Sign::sign($this->_pub_data, 2,$type);
        return $this->request($this->second_dir . $this->changeBankCardUrl, 'money',$type);
    }

    /**
     * Description:请求查询授信申请结果
     * Author: Sam
     * DateTime: 2019/1/5 17:44
     * @param $credit_id
     * @return mixed
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getLoanApplyStatus($credit_id)
    {
        $this->_pub_data = [
            'creditId' => $credit_id,
        ];
        $this->_pub_sign = Sign::sign($this->_pub_data, 2);
        return $this->request($this->second_dir . $this->get_loan_apply_status, 'money');
    }


    /**
     * Description: 获取用户放款结果
     * Author: liuju
     * DateTime: 2019-01-06 21:01
     * @param $loanId
     * @return mixed
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function queryLoanResult($loanId)
    {
        $this->_pub_data = [
            'loanId' => $loanId,
        ];
        $this->_pub_sign = Sign::sign($this->_pub_data, 2);
        return $this->request($this->second_dir . $this->loanResultUrl, 'money');
    }

    /**
     * Description: 获取loan_id
     * Author: ljf
     * DateTime: 2019-01-06 21:01
     * @param $loanId
     * @return mixed
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getLoanId($data)
    {
        $this->_pub_data = [
            'userId' => isset($data['uid']) ? $data['uid'] : '',
            'outTradeId' => isset($data['outTradeId']) ? $data['outTradeId'] : '',
            'loanId' => isset($data['loanId']) ? $data['loanId'] : '',
        ];
        $this->_pub_sign = Sign::sign($this->_pub_data, 2,2);
        return $this->request($this->second_dir . $this->loanResultUrl, 'money',2);
    }

    /**
     * Description:获取还款计划
     * Author:lijiafei
     * @param $data
     * @return mixed
     */
    public function getRepayPlan($data)
    {
        $this->_pub_data = [
            'loanId' => $data['loanId'],
            'period' => isset($data['period']) ? $data['period'] : 0,
        ];
        $dataType = RepaySummary::getDataTypeByLoanId($data['loanId']);
        $this->_pub_sign = Sign::sign($this->_pub_data, 2,$dataType);
        $result = $this->request($this->second_dir . $this->select_repay_plan, 'money',$dataType);
        Log::debug('get_repay_plan', ['result' => $result]);
        if ($result['code'] != ThirdMoneyCode::CODE_SUCCESS) {
            return false;
        }
        return $result;
    }

    /**
     * Description:提前试算还款试算
     * Author:lijiafei
     * @param $data
     * @return mixed
     */
    public function getRepaymentPlan($loanId)
    {
        $this->_pub_data = [
            'loanId' => $loanId,
        ];
        $dataType = RepaySummary::getDataTypeByLoanId($loanId);
        $this->_pub_sign = Sign::sign($this->_pub_data, 2,$dataType);
        $result = $this->request($this->second_dir . $this->repayment_repay, 'money',$dataType);
        if ($result['code'] != ThirdMoneyCode::CODE_SUCCESS) {
            Log::debug('还款:请求提前还清试算接口报错:' . json_encode($result, JSON_UNESCAPED_UNICODE));
            return false;
        }
        return $result;
    }

    /**
     * 主动还款
     */
    public function setMoneyRepay($data,$dataType = RepaySummary::DATA_TYPE_ONE)
    {
        $this->_pub_data = [
            'loanId' => $data['loanId'],
            'merOrderNo' => $data['merOrderNo'],
            'currentPeriod' => $data['currentPeriod'],
            'totalAmt' => $data['totalAmt'], //总金额
            'principalAmt' => $data['principalAmt'], //本金
            'interestAmt' => $data['interestAmt'], //利息
            'serviceAmt' => $data['serviceAmt'], //还款手续费
            'penaltyAmt' => $data['penaltyAmt'], //罚息
            'operateStatus' => $data['operateStatus'],
        ];
        $this->_pub_sign = Sign::sign($this->_pub_data, 2,$dataType);
        $result = $this->request($this->second_dir . $this->money_repay, 'money',$dataType);
        return $result;
    }

    /**
     * Description: 获取主动还款结果
     *
     * @param $data
     * @return bool|mixed
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getMoneyRepayResult($data)
    {
        $this->_pub_data = [
            'repayId' => $data['third_repay_id'],
            'merOrderNo' => $data['trade_no'],
        ];
        $this->_pub_sign = Sign::sign($this->_pub_data, 2);
        $result = $this->request($this->second_dir . $this->money_repay_result, 'money');
        Log::debug('repay_get_money_api' ,['result' => $result]);
        if ($result['code'] != ThirdMoneyCode::CODE_SUCCESS) {
            return false;
        }
        return $result;
    }

    /**
     * Description:贷款试算请求
     * Author: Sam
     * DateTime: 2019/1/8 16:41
     * @param $data
     * @return mixed
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function applyLoanCalculate($data)
    {
        $this->_pub_data = [
            'applyAmount' => $data['applyAmount'],
            'period' => $data['period'],
            'productNo' => config('common.money_platform_product_no'),
            'channel' => $data['channel'],
        ];
        $this->_pub_sign = Sign::sign($this->_pub_data, 2);
        return $this->request($this->second_dir . $this->loan_calculate, 'money');
    }

    /**
     * Description:月保费扣款
     * Author:lijiafei
     * @param $data
     */
    public function setMonthRepay($data)
    {
        $this->_pub_data = [
            'loanId' => $data['loanId'],
            'merOrderNo' => $data['merOrderNo'],
            'currentPeriod' => $data['currentPeriod'],
            'amount' => $data['amount']
        ];
        $dataType = RepaySummary::getDataTypeByLoanId($data['loanId']);
        $this->_pub_sign = Sign::sign($this->_pub_data, 2,$dataType);
        $result = $this->request($this->second_dir . $this->month_insurance_repay, 'money',$dataType);
        return $result;
    }

    /**
     * Description: 月保费扣款结果查询
     * Author: Gxs
     * @param $data
     * @return bool|mixed
     */
    public function getMonthRepayResult($data)
    {
        $this->_pub_data = [
            'recordId' => $data['third_record_id'],
        ];
        if (isset($data['trade_no']) && !empty($data['trade_no']))
            $this->_pub_data['merOrderNo'] = $data['trade_no'];
        $this->_pub_sign = Sign::sign($this->_pub_data, 2);
        $result = $this->request($this->second_dir . $this->month_insurance_repay_result, 'money');
        if ($result['code'] != ThirdMoneyCode::CODE_SUCCESS) {
            \Log::debug('repay_get_month_api', ['message' => $result['message']]);
            return false;
        }
        return $result;
    }

    /**
     * @description 商户代偿接口
     * @param $data
     * @return bool|mixed
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function PayCompensate($data)
    {
        $this->_pub_data = [
            'loanId' => $data['loanId'],
            'currentPeriod' => $data['currentPeriod'],
            'operateStatus' => 'D',
        ];
        $this->_pub_sign = Sign::sign($this->_pub_data, 2);
        $result = $this->request($this->second_dir . $this->pay_compensate, 'money');
        Log::debug('money_request_pay_compensate', ['loan_id' => $data['loanId'], 'result' => $result]);
        if ($result['code'] != ThirdMoneyCode::CODE_SUCCESS) {
            return ['flag' => false, 'result' => $result['message']];
        }
        return ['flag' => true, 'result' => $result];
    }

}